﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Pipes;
using System.IO;

namespace Lyon.Utility
{
    class NamedPipeConnection
    {
        static System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        static public object Receive(int id)
        {
            using (NamedPipeServerStream stream = new NamedPipeServerStream("ProcessCommunication" + id, PipeDirection.InOut, 10))
            {
                stream.WaitForConnection();
                StreamReader reader = new StreamReader(stream);
                string command = null;
                while ((command = reader.ReadLine()) == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                int dataLength = Convert.ToInt32(command);
                byte[] data = new byte[dataLength];
                stream.Read(data, 0, dataLength);
                using (MemoryStream dataStream = new MemoryStream(data))
                {
                    return formatter.Deserialize(dataStream);
                }
            }
        }

        static public void Send(int id, object value)
        {
            using (MemoryStream dataStream = new MemoryStream())
            {
                formatter.Serialize(dataStream, value);

                using (NamedPipeClientStream stream = new NamedPipeClientStream("ProcessCommunication" + id))
                {
                    stream.Connect(1000);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.WriteLine(dataStream.Length);
                    writer.Flush();
                    stream.WaitForPipeDrain();

                    dataStream.WriteTo(stream);
                }
            }
        }

    }
}
